package com.mililoan.console.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.TimerTask;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mililoan.common.bean.UserStatus;
import com.mililoan.console.bean.SysConfig;

/**
 * 删除在线列表
 * @author hozen 2014-6-26
 */
public class ClearOnline extends TimerTask {

    private static Logger LOGGER		= LoggerFactory.getLogger(ClearOnline.class);

    public void run() {
        this.clearOnline();
    }

    /**
     * 清空在线列表
     * @since hozen 2014-6-26
     */
    private void clearOnline() {

        HashMap statusHm = OnlineService.getStatusHm();
        List statusList = OnlineService.getStatusList();
        List newList = new ArrayList();

        //String keyStr="";
        Date touchDate = null;
        Date nowDate = new Date();
        Date logoutDate = null;
        UserStatus userStatus =null;

        if (statusList != null) {
            LOGGER.debug("###clearOnline start!size="+statusList.size());
            for (int i = 0; i < statusList.size(); i++) {
                userStatus = (UserStatus) statusList.get(i);
                logoutDate = userStatus.getLogoutDate();
                if(userStatus.isDeleted()){
	                long remainder = (nowDate.getTime()) - logoutDate.getTime();
	                if ( userStatus.isDeleted() && remainder > SysConfig.CLEAR_ONLINE_DELETED_TIME*60 * 1000) {//5 minites
	                    System.out.println("###clearOnline remove:!"+userStatus.getUserid());
	                    if(userStatus==statusHm.get(userStatus.getUserid() + "")){
	                        statusHm.remove(userStatus.getUserid() + ""); //从hashMap中清掉
	                    }
	                    continue;
	                }
                }
                newList.add(userStatus);
            }
            OnlineService.setStatusList(newList);
        }

        LOGGER.debug("###clearOnline done!size="+statusList.size());
//            while(iter.hasNext()){
//                userStatus = (UserStatus) iter.next();
//                touchDate = userStatus.getTouchDate();
//                long remainder = (nowDate.getTime()) - touchDate.getTime();
//                if ( remainder >3*60 * 1000) {//3 minites
//                    System.out.println("###clearOnline remove:!"+userStatus.getUserid());
//                    statusHm.remove(userStatus.getUserid()+"");//从hashMap中清掉
//                }
////                else if ( remainder >5*60 * 1000){
////                    userStatus.setViewStatus(UserStatus.Status.o);
////                }
//            }
//

    }

}
